﻿using System.Globalization;
using System.Text;

namespace Iot.Shared.Helper;

/// <summary>
/// </summary>
public static class HexHelper
{
    /// <summary>
    ///     byte 到 十六进制文本
    /// </summary>
    /// <param name="data">byte 数组集合</param>
    /// <param name="separate">分隔符</param>
    /// <param name="lower">是否小写 默认为true 小写</param>
    /// <returns></returns>
    public static string ByteToHexStr(this byte[] data, string separate, bool lower = true)
    {
        if (string.IsNullOrEmpty(separate)) return ByteToHexStr(data, lower);
        var sb = new StringBuilder();
        var a = lower ? 0x61 : 0x41;
        foreach (var item in data)
        {
            sb.Append(GetHexValue(item / 0x10, a));
            sb.Append(GetHexValue(item % 0x10, a));
            sb.Append(separate);
        }

        return sb.ToString();
    }

    /// <summary>
    ///     byte 到 十六进制文本
    /// </summary>
    /// <param name="data">byte 数组集合</param>
    /// <param name="lower">是否小写 默认为true 小写</param>
    /// <returns></returns>
    public static string ByteToHexStr(this byte[] data, bool lower = true)
    {
        if (data.Length < 1) return string.Empty;
        var a = lower ? 0x61 : 0x41;
        var cs = new char[data.Length * 2];
        for (int i = 0, j = 0; i < data.Length; i++, j += 2)
        {
            var b = data[i];
            cs[j] = GetHexValue(b / 0x10, a);
            cs[j + 1] = GetHexValue(b % 0x10, a);
        }

        return new string(cs);
    }

    private static char GetHexValue(int i, int a)
    {
        return i switch
        {
            < 10 => (char)(i + 0x30),
            _ => (char)(i - 10 + a)
        };
    }

    /// <summary>
    ///     十六进制文本到 byte 集合
    /// </summary>
    /// <param name="hexString">十六进制文本</param>
    /// <returns></returns>
    public static byte[] HexStrToByte(this string hexString)
    {
        //替换空格 换行
        hexString = hexString.Trim()
            .Replace("-", null)
            .Replace("0x", null)
            .Replace("0X", null)
            .Replace(" ", null)
            .Replace("\r", null)
            .Replace("\n", null)
            .Replace(",", null);
        var returnBytes = new byte[hexString.Length / 2];
        for (var i = 0; i < returnBytes.Length; i++)
            returnBytes[i] = byte.Parse(hexString.Substring(i * 2, 2), NumberStyles.HexNumber);
        return returnBytes;
    }
}